package com.junzhiit.nengji.app.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.junzhiit.nengji.app.service.BrandService;
import com.junzhiit.nengji.app.web.exception.BrandIsExistException;
import com.junzhiit.nengji.app.web.exception.BrandNotFoundException;
import com.junzhiit.nengji.app.web.exception.NameIsExistException;
import com.junzhiit.nengji.app.web.util.OrderNumberUtils;
import com.junzhiit.nengji.app.web.util.ViewObjectUtil;
import com.junzhiit.nengji.app.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.app.web.vo.BrandAddVO;
import com.junzhiit.nengji.app.web.vo.BrandAllVO;
import com.junzhiit.nengji.app.web.vo.BrandEditVO;
import com.junzhiit.nengji.app.web.vo.BrandVO;
import com.junzhiit.nengji.app.web.vo.DataTablesParamVO;
import com.junzhiit.nengji.app.web.vo.ResultVO;
import com.junzhiit.nengji.app.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.dao.BrandDAO;
import com.junzhiit.nengji.dao.cache.BrandCacheDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Brand;
import com.junzhiit.nengji.model.enums.LoginType;

@Service
public class BrandServiceImpl extends BaseServiceImpl implements BrandService {

	@Autowired
	private BrandDAO brandDAO;

	@Autowired
	private BrandCacheDAO brandCacheDAO;

	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;

	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.brand}")
	private String brandPath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;

	@Override
	public Map<String, Object> findAll( DataTablesParamVO dtp, BrandVO brandVO) {
		Brand brand = new Brand();
		BeanUtils.copyProperties(brandVO, brand);

		String key = DIYKey.getSessionHashKey(brandVO.getSessionId());
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			brand.setShopId(session.getSystemId());
		}

		List<Brand> list = brandDAO.findAll(dtp.getStart(), dtp.getLength(), brand);

		int totalCount = brandDAO.getTotalCount(brand);

		return ViewObjectUtil.dataTables(list, dtp.getDraw(), totalCount);
	}

	@Override
	@Transactional
	public ResultVO add(String sessionId, BrandAddVO brandAddVO) {
		ResultVO resultVO = new ResultVO();
		Brand brand = new Brand();
		BeanUtils.copyProperties(brandAddVO, brand);

		String key = DIYKey.getSessionHashKey(sessionId);
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			brand.setShopId(session.getSystemId());
		}

		int count = brandDAO.getBrandExist(brand);
		if (count > 0) {
			throw new BrandIsExistException("品牌已经存在");
		}

		Long index = brandCacheDAO.incr(DIYKey.getBrandCodeStringKey());
		String code = OrderNumberUtils.getSystemCode(OrderNumberUtils.BRAND_NUMBER_PREFIX, index.intValue());
		brand.setCode(code);

		Brand param= brandDAO.insert(brand);
		resultVO.setData(param);
		boolean is = false;
		if(StringUtils.isNotBlank(brand.getLogoImgUrl())){
			is = AliyunOSSClientUtil.moveFile(backetName,brand.getLogoImgUrl(), brandPath, uploadPath);
		}
		if(is){
			AliyunOSSClientUtil.removeFile(backetName, uploadPath+brand.getLogoImgUrl());
		}
		return resultVO;
	}

	@Override
	public ResultVO delete(String id) {
		ResultVO resultVO = new ResultVO();
		try {
			resultVO.setData(brandDAO.updateToDelete(id));
		} catch (Exception e) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		return resultVO;
	}

	@Override
	@Transactional
	public ResultVO edit(BrandEditVO brandEditVO) {
		ResultVO resultVO = new ResultVO();
		Brand param = brandDAO.query(brandEditVO.getId());

		if (param == null) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		if (!param.getName().equals(brandEditVO.getName())) {
			Brand brand = new Brand();
			BeanUtils.copyProperties(brandEditVO, brand);
			brand.setShopId(param.getShopId());
			if (brandDAO.getBrandExist(brand) > 0) {
				throw new NameIsExistException("品牌名称已经存在");
			}
		}
		if (StringUtils.isNotBlank(brandEditVO.getLogoImgUrl())
				&& !brandEditVO.getLogoImgUrl().equals(param.getLogoImgUrl())) {
			//FileUtil.moveFile(uploadPath + brandEditVO.getLogoImgUrl(), brandPath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,brandEditVO.getLogoImgUrl(), brandPath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+brandEditVO.getLogoImgUrl());
			}
		}

		BeanUtils.copyProperties(brandEditVO, param);
		param.setUpdatedTime(new Date());

		resultVO.setData(brandDAO.update(param));
		return resultVO;
	}

	@Override
	public ResultVO findById(String id) {
		ResultVO resultVO = new ResultVO();
		Brand brand = brandDAO.query(id);
		if (brand == null) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		resultVO.setData(brand);
		return resultVO;
	}

	@Override
	public ResultVO findAlls(String sessionId) {
		ResultVO resultVO = new ResultVO();
		
		String key = DIYKey.getSessionHashKey(sessionId);
		SystemUserSessionVO session = systemUserCacheDAO.getHash(key, SystemUserSessionVO.class);
		String shopId=null;
		if (LoginType.SHOP.toIntType() == session.getLoginType()) {
			shopId=session.getSystemId();
		}
		
		List<Brand> brands = brandDAO.findAlls(shopId);
		List<BrandAllVO> brandAllVOs = new ArrayList<BrandAllVO>();
		for (Brand brand : brands) {
			BrandAllVO brandAllVO = new BrandAllVO();
			BeanUtils.copyProperties(brand, brandAllVO);
			brandAllVOs.add(brandAllVO);
		}
		resultVO.setData(brandAllVOs);
		return resultVO;
	}

	@Override
	public ResultVO delBrandPic(String id)  {
		ResultVO result = new ResultVO();

		Brand brand = brandDAO.query(id);
		if (brand == null) {
			throw new BrandNotFoundException("该品牌不存在！");
		}
		if(StringUtils.isNotBlank(brand.getLogoImgUrl())){
			//boolean flag = FileUtil.removeFile(brandPath + brand.getLogoImgUrl());
			boolean flag = AliyunOSSClientUtil.removeFile(backetName, brandPath+brand.getLogoImgUrl());

			brand.setLogoImgUrl(null);
			brand.setUpdatedTime(new Date());
			brandDAO.update(brand, true);

			result.setData(flag);
		}else{
			result.setData(true);
		}
		return result;
	}

}
